package com.db.adjust;


import android.net.NetworkInfo;
import android.text.TextUtils;
import com.db.main.IOSDevice;
import com.db.main.Task;
import com.db.utils.ISOMap;
import com.db.utils.Util;
import org.json.JSONObject;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by pfms on 06/11/14.
 */
public class DeviceInfo {

    private static final String OFFICIAL_FACEBOOK_SIGNATURE =
            "30820268308201d102044a9c4610300d06092a864886f70d0101040500307a310b3009060355040613" +
                    "025553310b3009060355040813024341311230100603550407130950616c6f20416c746f31" +
                    "183016060355040a130f46616365626f6f6b204d6f62696c653111300f060355040b130846" +
                    "616365626f6f6b311d301b0603550403131446616365626f6f6b20436f72706f726174696f" +
                    "6e3020170d3039303833313231353231365a180f32303530303932353231353231365a307a" +
                    "310b3009060355040613025553310b30090603550408130243413112301006035504071309" +
                    "50616c6f20416c746f31183016060355040a130f46616365626f6f6b204d6f62696c653111" +
                    "300f060355040b130846616365626f6f6b311d301b0603550403131446616365626f6f6b20" +
                    "436f72706f726174696f6e30819f300d06092a864886f70d010101050003818d0030818902" +
                    "818100c207d51df8eb8c97d93ba0c8c1002c928fab00dc1b42fca5e66e99cc3023ed2d214d" +
                    "822bc59e8e35ddcf5f44c7ae8ade50d7e0c434f500e6c131f4a2834f987fc46406115de201" +
                    "8ebbb0d5a3c261bd97581ccfef76afc7135a6d59e8855ecd7eacc8f8737e794c60a761c536" +
                    "b72b11fac8e603f5da1a2d54aa103b8a13c0dbc10203010001300d06092a864886f70d0101" +
                    "040500038181005ee9be8bcbb250648d3b741290a82a1c9dc2e76a0af2f2228f1d9f9c4007" +
                    "529c446a70175c5a900d5141812866db46be6559e2141616483998211f4a673149fb2232a1" +
                    "0d247663b26a9031e15f84bc1c74d141ff98a02d76f85b2c8ab2571b6469b232d8e768a7f7" +
                    "ca04f7abe4a775615916c07940656b58717457b42bd928a2";

    String playAdId;
    String playAdIdSource;
    int playAdIdAttempt;
    Boolean isTrackingEnabled;
    private boolean nonGoogleIdsReadOnce = false;
    String macSha1;
    String macShortMd5;
    String androidId;
    String fbAttributionId;
    String clientSdk;
    String packageName;
    String appVersion;
    String deviceType;
    String deviceName;
    String deviceManufacturer;
    String osName;
    String osVersion;
    String apiLevel;
    String language;
    String country;
    String screenSize;
    String screenFormat;
    String screenDensity;
    String displayWidth;
    String displayHeight;
    String hardwareName;
    String abi;
    String buildName;
    String appInstallTime;
    String appUpdateTime;


    String mcc;
    String mnc;

    NetworkInfo networkInfo;


    String bundleID;
    String shortVersion;
    String idfv;
    String idfa;
    String primaryDedupeToken;
    String attStatus;

    //adjconfig init time
    String skadnRegisteredAt;
    //ios boot time,like 2024-02-17T22:08:15.000Z-0800
    String startAt;

    boolean hasFbAnonId;

    //    public static DeviceInfo parseDeviceInfo(String deviceStr,String sdkPrefix,String appStr){
    public static DeviceInfo parseDeviceInfo(JSONObject deviceJson, JSONObject appJson, String iso) {
        DeviceInfo deviceInfo = new DeviceInfo();
        deviceInfo.networkInfo = new NetworkInfo();
        JSONObject androidJson = deviceJson.getJSONObject("androidInfo");
        JSONObject gaJson = deviceJson.getJSONObject("gaInfo");

        int screenLayout = androidJson.getInt("screenLayout");
        deviceInfo.deviceType = deviceInfo.getDeviceType(screenLayout);
        deviceInfo.deviceName = androidJson.getString("model"); // Build.MODEL
        deviceInfo.deviceManufacturer = androidJson.getString("manufacturer");
        deviceInfo.osName = getOsName();
        deviceInfo.osVersion = androidJson.getString("release");
        deviceInfo.apiLevel = "" + androidJson.getInt("sdkInt");

        //todo check
//        deviceInfo.language = gaJson.optString("language", ISOMap.ISO_LANGUAGE_MAP.get(iso));
        deviceInfo.language = ISOMap.ISO_LANGUAGE_MAP.get(iso);
//        deviceInfo.country = gaJson.optString("country",iso);
        deviceInfo.country = iso;

        deviceInfo.screenSize = deviceInfo.getScreenSize(screenLayout);
        deviceInfo.screenFormat = deviceInfo.getScreenFormat(screenLayout);
        deviceInfo.screenDensity = deviceInfo.getScreenDensity(androidJson.getInt("densityDpi"));
        deviceInfo.displayWidth = deviceInfo.getDisplayWidth(androidJson.getInt("widthPixels"));
        deviceInfo.displayHeight = deviceInfo.getDisplayHeight(androidJson.getInt("heightPixels"));
        deviceInfo.clientSdk = deviceInfo.getClientSdk(appJson.optString("sdkPrefix", null), appJson.getString("clientSdk"));
        deviceInfo.fbAttributionId = deviceInfo.getFacebookAttributionId(null);
        String display = null;
        JSONObject propertyJson = new JSONObject(androidJson.getString("systemProperties"));
        try {
            Object dispObj = androidJson.get("display");
//            System.out.println("dispObj:" + dispObj);

            if (dispObj == null || "null".equals(dispObj.toString())) {
                display = propertyJson.getString("ro.build.display.id");
            } else {
//                System.out.println("xxxx");
                display = dispObj.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
//        System.out.println("display:" + display);
        deviceInfo.hardwareName = display;//todo Build.DISPLAY, ro.build.display.id
//        hardwareName = machine.android.D;
        //todo ro.product.cpu.abilis
        String abi = "arm64-v8a";
        try {
            abi = propertyJson.getString("ro.product.cpu.abilist").split(",")[0];
        } catch (Exception e) {
            e.printStackTrace();
        }
        deviceInfo.abi = abi;

        String buildId = androidJson.optString("buildId", null);
        if (buildId == null) {
            String ua = androidJson.optString("ua", null);
            if (ua == null) {
                ua = gaJson.optString("ua", null);
            }
            if (ua != null) {
                buildId = getBuildIdFromUA(ua);
            }
        }
        deviceInfo.buildName = buildId;//get from builid or UA  getBuildName();

        deviceInfo.appVersion = appJson.getString("versionName");
        //todo need to be check
        long now = System.currentTimeMillis();
        deviceInfo.appInstallTime = getAppInstallTime(now, iso);
        deviceInfo.appUpdateTime = getAppUpdateTime(now, iso);

//        deviceInfo.mcc = gaJson.optString("mcc", ISOMap.ISO_MCC_MAP.get(iso));
        deviceInfo.mcc = ISOMap.ISO_MCC_MAP.get(iso);
        deviceInfo.mnc = gaJson.optString("mnc", "001");

        deviceInfo.networkInfo.type = 1;
        deviceInfo.networkInfo.connectedOrConnecting = true;
        deviceInfo.playAdId = gaJson.getString("gaId");
        deviceInfo.playAdIdSource = "service";
        deviceInfo.playAdIdAttempt = 1;//[1,3]
        deviceInfo.packageName = appJson.getString("packageName");

        return deviceInfo;
    }

    public static DeviceInfo parseDeviceInfoIOS(IOSDevice iosDevice, JSONObject appJson, String iso) {
//        IOSDevice iosDevice = IOSDevice.getInstance();

        DeviceInfo deviceInfo = new DeviceInfo();
        deviceInfo.playAdIdAttempt = -1;
        deviceInfo.networkInfo = new NetworkInfo();
        deviceInfo.networkInfo.type = -1;
        deviceInfo.networkInfo.connectedOrConnecting = true;

        deviceInfo.deviceType = IOSDevice.deviceType;
        deviceInfo.deviceName = iosDevice.deviceName;
        deviceInfo.osName = IOSDevice.osName;
        deviceInfo.osVersion = iosDevice.osVersion;

        deviceInfo.clientSdk = deviceInfo.getClientSdk(appJson.optString("sdkPrefix", null), appJson.getString("clientSdk"));
        deviceInfo.appVersion = appJson.getString("versionName");
        long now = System.currentTimeMillis();
        deviceInfo.appInstallTime = getAppInstallTime(now, iso);//installed_at

        deviceInfo.bundleID = appJson.optString("bundleID", null);
        deviceInfo.shortVersion = appJson.optString("shortVersion", "");
        deviceInfo.idfa = iosDevice.idfa;
        deviceInfo.idfv = iosDevice.idfv;
        deviceInfo.primaryDedupeToken = UUID.randomUUID().toString();
        deviceInfo.attStatus = "3";
        deviceInfo.startAt = iosDevice.startTime;
        deviceInfo.hasFbAnonId = appJson.optBoolean("hasFbAnonId", false);

        return deviceInfo;
    }

    public DeviceInfo() {

    }

    private static String getBuildIdFromUA(String ua) {
        if (TextUtils.isEmpty(ua))
            return null;
        Pattern p = Pattern.compile(".*Build/(.*);.*");
        Matcher m = p.matcher(ua);
        if (m.find()) {
            return m.group(1);
        }
        return null;
    }

    public static void main(String[] args) {
//        String ua = "Mozilla/5.0 (Linux; Android 11; CPH1989 Build/RP1A.200720.011; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/107.0.5304.91 Mobile Safari/537.36";
//        String ua = "Mozilla/5.0 (Linux; Android 11; moto g power (2022) Build/RRQS31.Q3-68-140-10; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/106.0.5249.126 Mobile Safari/537.3636";
//        String ua = "Mozilla/5.0 (Linux; Android 11; CPH1989 Build/MRA58N; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/107.0.5304.91 Mobile Safari/537.36";
//        getBuildIdFromUA(ua);


//        byte[] encrypts = Task.xor("{\"sdkPrefix\":\"\",\"clientSdk\":\"android4.28.4\",\"versionName\":\"2.1.15\",\"packageName\":\"com.zain.pay\",\"appSecret\":\"\",\"appToken\":\"ccgss41tyjgg\",\"defaultTracker\":\"\",\"deviceKnown\":null,\"environment\":\"production\",\"eventBufferingEnabled\":false,\"secretId\":\"\"}".getBytes(),"adjust-key1");
//        byte[] encrypts = Task.xor("{\"packageName\":\"com.noon.buyerapp\",\"versionName\":\"4.3 (3458)\",\"sdkPrefix\":\"react-native4.33.0\",\"clientSdk\":\"react-native4.33.0@android4.33.2\",\"environment\":\"production\",\"eventBufferingEnabled\":false,\"appToken\":\"2yieufhrm3r4\"}".getBytes(),"adjust-key1");


        byte[] encrypts = Task.xor("{\"sdkPrefix\":\"react-native4.33.0\",\"clientSdk\":\"ios4.33.3\",\"versionName\":\"3503\",\"shortVersion\":\"4.4\",\"bundleID\":\"com.noon.buyerapp\",\"appSecret\":\"\",\"appToken\":\"2yieufhrm3r4\",\"defaultTracker\":\"\",\"environment\":\"production\",\"eventBufferingEnabled\":false,\"secretId\":\"\"}".getBytes(), "adjust-key1");
        String encStr = Base64.getEncoder().encodeToString(encrypts);
        encStr = "GkYPGwUdXwQLFFQPEEhPUQRfBAEMUhUNBRtRWA8OExxfFSYfExURXwILHnQPBQgZFhAPUQMYXRIBRlcSBF0/ChJUD0ZQVxQMWB0dCUQFUQYUS1YBSRUYUgoFDRA9FUAOR0MTExFEBxoCSAwEDFIJAUQUAwQPR0cPVBMXAxodOkwGAFsLQ1dEREtaHkYCFEJDSEgGFx99GQAfWBlGUBsGGEFHRxpdCAEEASAQRklfW1APABgaGhAZRVZMH1BGFw==";
        System.out.println("encStr:" + encStr);
//        System.out.println("tryto:" + new String(Base64.getDecoder().decode(encStr)));
        String plain = new String(Task.xor(Base64.getDecoder().decode(encStr), "adjust-key1"));
        System.out.println("plain:" + plain);

        System.out.println("appSecret:" + Util.formatString("%d%d%d%d", 0x62812041, 0x70776331, 0x4ba6f33b, 0x479073c8).length());
        System.out.println("appSecret:" + "182621014515585101881036106404672521758".length());


//        String bf = "{\\\"packageName\\\":\\\"br.com.intermedium\\\",\\\"versionName\\\":\\\"13.0.6\\\",\\\"clientSdk\\\":\\\"android4.33.3\\\",\\\"environment\\\":\\\"production\\\",\\\"eventBufferingEnabled\\\":true,\\\"appToken\\\":\\\"mlciug5mbnk0\\\",\\\"callback_params\\\":\\\"{\\\\\\\"account_context\\\\\\\":\\\\\\\"PF\\\\\\\",\\\\\\\"osLanguage\\\\\\\":\\\\\\\"zh\\\\\\\",\\\\\\\"macAddress\\\\\\\":\\\\\\\"81d6bd0e74fa6796\\\\\\\"}\\\"}";
//
//        System.out.println("bf:" + bf);
//
//        System.out.println("bf:" + bf.replace("\\\"","\""));
    }


    private String getDeviceType(int screenLayout) {
//        int screenSize = screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK;
        int screenSize = screenLayout & 0x0f;

        switch (screenSize) {
//            case Configuration.SCREENLAYOUT_SIZE_SMALL:
            case 0x01:
//            case Configuration.SCREENLAYOUT_SIZE_NORMAL:
            case 0x02:
                return "phone";
//            case Configuration.SCREENLAYOUT_SIZE_LARGE:
            case 0x03:
            case 4:
                return "tablet";
            default:
                return null;
        }
    }


    private static String getOsName() {
        return "android";
    }


    private String getLanguage(Locale locale) {
        return locale.getLanguage();
    }

    private String getCountry(Locale locale) {
        return locale.getCountry();
    }


    private String getScreenSize(int screenLayout) {
        int screenSize = screenLayout & 0x0f;
        switch (screenSize) {
            case 0x01:
                return "small";
            case 0x02:
                return "normal";
            case 0x03:
                return "large";
            case 4:
                return "xlarge";
            default:
                return null;
        }
    }

    private String getScreenFormat(int screenLayout) {
        int screenFormat = screenLayout & 0x30;

        switch (screenFormat) {
            case 0x20:
                return "long";
            case 0x10:
                return "normal";
            default:
                return null;
        }
    }

    private String getScreenDensity(int density) {
        int low = (160 + 120) / 2;
        int high = (160 + 240) / 2;

        if (density == 0) {
            return null;
        } else if (density < low) {
            return "low";
        } else if (density > high) {
            return "high";
        }
        return "medium";
    }

    private String getDisplayWidth(int widthPixels) {
        return String.valueOf(widthPixels);
    }

    private String getDisplayHeight(int heightPixels) {
        return String.valueOf(heightPixels);
    }

    private String getClientSdk(String sdkPrefix, String sdk) {
        if (TextUtils.isEmpty(sdkPrefix)) {
            return sdk;
        } else {
            return Util.formatString("%s@%s", sdkPrefix, sdk);
        }
    }

    private String getMacSha1(String macAddress) {
        if (macAddress == null) {
            return null;
        }
        String macSha1 = Util.sha1(macAddress);

        return macSha1;
    }

    private String getMacShortMd5(String macAddress) {
        if (macAddress == null) {
            return null;
        }
        String macShort = macAddress.replaceAll(":", "");
        String macShortMd5 = Util.md5(macShort);

        return macShortMd5;
    }

    //    private String getFacebookAttributionId(final Context context) {
    private String getFacebookAttributionId(String fbAid) {
        return fbAid;
//        try {
//            @SuppressLint("PackageManagerGetSignatures")
//            Signature[] signatures = context.getPackageManager().getPackageInfo(
//                    "com.facebook.katana",
//                    PackageManager.GET_SIGNATURES).signatures;
//            if (signatures == null || signatures.length != 1) {
//                // Unable to find the correct signatures for this APK
//                return null;
//            }
//            Signature facebookApkSignature = signatures[0];
//            if (!OFFICIAL_FACEBOOK_SIGNATURE.equals(facebookApkSignature.toCharsString())) {
//                // not the official Facebook application
//                return null;
//            }
//
//            final ContentResolver contentResolver = context.getContentResolver();
//            final Uri uri = Uri.parse("content://com.facebook.katana.provider.AttributionIdProvider");
//            final String columnName = "aid";
//            final String[] projection = {columnName};
//            final Cursor cursor = contentResolver.query(uri, projection, null, null, null);
//
//            if (cursor == null) {
//                return null;
//            }
//            if (!cursor.moveToFirst()) {
//                cursor.close();
//                return null;
//            }
//
//            final String attributionId = cursor.getString(cursor.getColumnIndex(columnName));
//            cursor.close();
//            return attributionId;
//        } catch (Exception e) {
//            return null;
//        }
    }


    private static String getAppInstallTime(long firstInstallTime, String iso) {
//        String appInstallTime = Util.dateFormatter.format(new Date(firstInstallTime));
        String appInstallTime = Util.format(new Date(firstInstallTime), iso);
        return appInstallTime;
    }

    private static String getAppUpdateTime(long lastUpdateTime, String iso) {
//        String appInstallTime = Util.dateFormatter.format(new Date(lastUpdateTime));
        String appInstallTime = Util.format(new Date(lastUpdateTime), iso);
        return appInstallTime;
    }
}
